//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package admin_docker_template_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas/api-server/admin_api_serv/admin_common"
	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/docker_dao"
	"atomgit.com/openlinksaas/api-server/dao/fs_dao"
	"atomgit.com/openlinksaas/proto-gen-go.git/docker_template_api"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
)

func (apiImpl *DockerTemplateAdminImpl) CreateApp(ctx context.Context, req *docker_template_api.AdminCreateAppRequest) (*docker_template_api.AdminCreateAppResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &docker_template_api.AdminCreateAppResponse{
			Code:   docker_template_api.AdminCreateAppResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &docker_template_api.AdminCreateAppResponse{
			Code:   docker_template_api.AdminCreateAppResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.DockerTemplatePerm.CreateApp {
		return &docker_template_api.AdminCreateAppResponse{
			Code:   docker_template_api.AdminCreateAppResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	//检查分类是否存在
	exist, err := docker_dao.CateDao.Exist(ctx, req.CateId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &docker_template_api.AdminCreateAppResponse{
			Code:   docker_template_api.AdminCreateAppResponse_CODE_NO_CATE,
			ErrMsg: "分类信息不存在",
		}, nil
	}
	//检查文件是否存在
	if req.IconFileId != "" {
		dtFsId, err := fs_dao.GlobalFsDao.GetDockerTemplateFs(ctx)
		if err != nil {
			return nil, err
		}
		exist, err = fs_dao.FsFileDao.Exist(ctx, dtFsId, req.IconFileId)
		if err != nil {
			return nil, err
		}
		if !exist {
			return &docker_template_api.AdminCreateAppResponse{
				Code:   docker_template_api.AdminCreateAppResponse_CODE_NO_FILE,
				ErrMsg: "文件不存在",
			}, nil
		}
	}

	appId := uuid.NewString()
	nowTime := time.Now().UnixNano() / 1e6

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = docker_dao.AppDao.Insert(sessCtx, &docker_dao.AppInfoDbItem{
			AppId:         appId,
			Name:          req.Name,
			Desc:          req.Desc,
			IconFileId:    req.IconFileId,
			CateId:        req.CateId,
			OfficialUrl:   req.OfficialUrl,
			DocUrl:        req.DocUrl,
			TemplateCount: 0,
			CreateTime:    nowTime,
			UpdateTime:    nowTime,
			GoodCount:     0,
		})
		if err != nil {
			return nil, err
		}
		count, err := docker_dao.AppDao.Count(sessCtx, true, req.CateId, false, "")
		if err != nil {
			return nil, err
		}
		err = docker_dao.CateDao.UpdateAppCount(sessCtx, req.CateId, count)
		if err != nil {
			return nil, err
		}
		return &docker_template_api.AdminCreateAppResponse{
			Code:  docker_template_api.AdminCreateAppResponse_CODE_OK,
			AppId: appId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*docker_template_api.AdminCreateAppResponse), nil
}

func (apiImpl *DockerTemplateAdminImpl) UpdateApp(ctx context.Context, req *docker_template_api.AdminUpdateAppRequest) (*docker_template_api.AdminUpdateAppResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &docker_template_api.AdminUpdateAppResponse{
			Code:   docker_template_api.AdminUpdateAppResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &docker_template_api.AdminUpdateAppResponse{
			Code:   docker_template_api.AdminUpdateAppResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.DockerTemplatePerm.UpdateApp {
		return &docker_template_api.AdminUpdateAppResponse{
			Code:   docker_template_api.AdminUpdateAppResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	//检查应用是否存在
	appItem, err := docker_dao.AppDao.Get(ctx, req.AppId)
	if err != nil {
		return &docker_template_api.AdminUpdateAppResponse{
			Code:   docker_template_api.AdminUpdateAppResponse_CODE_NO_APP,
			ErrMsg: "应用不存在",
		}, nil
	}

	//检查分类是否存在
	exist, err := docker_dao.CateDao.Exist(ctx, req.CateId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &docker_template_api.AdminUpdateAppResponse{
			Code:   docker_template_api.AdminUpdateAppResponse_CODE_NO_CATE,
			ErrMsg: "分类信息不存在",
		}, nil
	}
	//检查文件是否存在
	if req.IconFileId != "" {
		dtFsId, err := fs_dao.GlobalFsDao.GetDockerTemplateFs(ctx)
		if err != nil {
			return nil, err
		}
		exist, err = fs_dao.FsFileDao.Exist(ctx, dtFsId, req.IconFileId)
		if err != nil {
			return nil, err
		}
		if !exist {
			return &docker_template_api.AdminUpdateAppResponse{
				Code:   docker_template_api.AdminUpdateAppResponse_CODE_NO_FILE,
				ErrMsg: "文件不存在",
			}, nil
		}
	}
	nowTime := time.Now().UnixNano() / 1e6

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = docker_dao.AppDao.Update(sessCtx, req.AppId, req.Name, req.Desc, req.IconFileId, req.CateId, req.OfficialUrl, req.DocUrl, nowTime)
		if err != nil {
			return nil, err
		}
		if appItem.CateId != req.CateId {
			count, err := docker_dao.AppDao.Count(sessCtx, true, appItem.CateId, false, "")
			if err != nil {
				return nil, err
			}
			err = docker_dao.CateDao.UpdateAppCount(sessCtx, appItem.CateId, count)
			if err != nil {
				return nil, err
			}

			count, err = docker_dao.AppDao.Count(sessCtx, true, req.CateId, false, "")
			if err != nil {
				return nil, err
			}
			err = docker_dao.CateDao.UpdateAppCount(sessCtx, req.CateId, count)
			if err != nil {
				return nil, err
			}
		}
		return &docker_template_api.AdminUpdateAppResponse{
			Code: docker_template_api.AdminUpdateAppResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*docker_template_api.AdminUpdateAppResponse), nil
}

func (apiImpl *DockerTemplateAdminImpl) RemoveApp(ctx context.Context, req *docker_template_api.AdminRemoveAppRequest) (*docker_template_api.AdminRemoveAppResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &docker_template_api.AdminRemoveAppResponse{
			Code:   docker_template_api.AdminRemoveAppResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &docker_template_api.AdminRemoveAppResponse{
			Code:   docker_template_api.AdminRemoveAppResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.DockerTemplatePerm.RemoveApp {
		return &docker_template_api.AdminRemoveAppResponse{
			Code:   docker_template_api.AdminRemoveAppResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	appItem, err := docker_dao.AppDao.Get(ctx, req.AppId)
	if err != nil {
		return &docker_template_api.AdminRemoveAppResponse{
			Code:   docker_template_api.AdminRemoveAppResponse_CODE_NO_APP,
			ErrMsg: "应用不存在",
		}, nil
	}
	if appItem.TemplateCount > 0 {
		return &docker_template_api.AdminRemoveAppResponse{
			Code:   docker_template_api.AdminRemoveAppResponse_CODE_HAS_TEMPLATE,
			ErrMsg: "还有模板未删除",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = docker_dao.AppDao.Remove(sessCtx, req.AppId)
		if err != nil {
			return nil, err
		}
		count, err := docker_dao.AppDao.Count(sessCtx, true, appItem.CateId, false, "")
		if err != nil {
			return nil, err
		}
		err = docker_dao.CateDao.UpdateAppCount(sessCtx, appItem.CateId, count)
		if err != nil {
			return nil, err
		}
		err = docker_dao.AppImageDao.RemoveByApp(sessCtx, req.AppId)
		if err != nil {
			return nil, err
		}
		return &docker_template_api.AdminRemoveAppResponse{
			Code: docker_template_api.AdminRemoveAppResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*docker_template_api.AdminRemoveAppResponse), nil
}
